package com.ruoyi.web.controller.shopping.filter;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.shopping.JwtUtil;
import com.ruoyi.web.controller.shopping.common.BaseContext;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter("/*")
public class TokenFilter implements Filter {
    private static String[] noFilterPath = {
            "/xiaomi/v2/ms/user/login",
            "/xiaomi/v2/ms/user/register",
            "/xiaomi/v2/carousel",
            "/xiaomi/v2/product/hot",
            "/xiaomi/v2/product",
            "/xiaomi/v2/category",
            "/xiaomi/v2/carousel",
            "/profile"
    };

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        System.out.println(httpServletRequest.getRequestURL());
        System.out.println(httpServletRequest.getServletPath());
        //判断是否有token
        String token = httpServletRequest.getHeader("Authorization");
        if (StringUtils.isEmpty(token)) {
            Boolean flag = false;
            for (String s : noFilterPath) {
                if (httpServletRequest.getRequestURL().toString().contains(s)) {
                    flag = true;
                }
            }
            if (flag) {
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
            servletResponse.setContentType("text/html;charset=utf-8");
            servletResponse.getWriter().write("请登录");
            return;
        }
        try {
            String userId = JwtUtil.getParam(JwtUtil.vailToken(token), "userId");
//            HeaderMapRequestWrapper headerMapRequestWrapper = new HeaderMapRequestWrapper(httpServletRequest);
//            headerMapRequestWrapper.addHeader("userId",userId);
            BaseContext.setId(Integer.valueOf(userId));
            filterChain.doFilter(servletRequest, servletResponse);
        }catch (Exception e){
            Boolean flag = false;
            for (String s : noFilterPath) {
                if (httpServletRequest.getRequestURL().toString().contains(s)) {
                    flag = true;
                }
            }
            if (flag) {
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
            servletResponse.setContentType("text/html;charset=utf-8");
            servletResponse.getWriter().write("请登录");
        }

    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
